import {defineStore} from "pinia";

/**
 * 默认地址
 */
export const defRegion = {
  ac: "000000",
  domain: "",
  text: "邯郸",
  id: "0",
};

export const home = defineStore({
  id: "home",
  state: () => ({
    region: uni.getStorageSync("region") || defRegion,
    ac: uni.getStorageSync("ac") || defRegion.ac,
    searchHistory: uni.getStorageSync("searchHistory"),
  }),
  actions: {
    // 修改地区
    changeRegion(payload: any) {
      this.region = payload;
      this.ac = payload.ac;
    },
    // 历史记录操作
    changeSearchHistory(payload: {
      type: string;
      text: string;
      index: number;
    }) {
      const { type, text, index } = payload; // 对象解构赋值
      switch (type) {
        case "add":
          this.searchHistory.push({
            text,
            time: new Date(),
          });
          break;
        case "delete":
          this.searchHistory.splice(index, 1);
          uni.setStorageSync("searchHistory", this.searchHistory);
          break;
        case "clear":
          this.searchHistory = [];
          break;
      }
    },
  },
});
